import time

from analyze.analyzer import JsonAnalyzer
from download.sub.ItJuZi_downloader import ItJuZiDownloader
from handle.handler import BasicHandler
import logging
import traceback

from store.sub.itjuzi import ItJuZiInvestmentsProjectStore


class ItJuZiProjectHandler(BasicHandler):
    def __init__(self, config):
        super(ItJuZiProjectHandler, self).__init__(config)
        self.mdb = config['mdb']

    def get_downloader(self):
        return ItJuZiDownloader(self.config)

    def get_analyzer(self):
        return JsonAnalyzer()

    def get_store(self):
        return ItJuZiInvestmentsProjectStore(self.config)

    def duplicated_key(self, task):
        return 'duplicated:{}:{}'.format(self.name, task['project_id'])

    def save(self, result, task):
        time.sleep(3)
        try:
            result = result.json()
            code = result['code']
            if code == 200:
                result = result['data']
                result['projectid'] = task['project_id']
                self.store.set(self.store.table, result)
                self.mdb.commit()
        except Exception as e:
            logging.error(e)
            logging.error(traceback.format_exc())
